/*
 * Copyright 2010 Aekold Helbrass
 *
 * This file is part of RosterComposer.
 *
 * RosterComposer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * RosterComposer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with RosterComposer.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.heresylabs.rostercomposer;

import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import org.heresylabs.rostercomposer.roster.RosterEntry;
import org.heresylabs.rostercomposer.units.Option;

/**
 *
 * @author Aekold Helbrass <Helbrass@gmail.com>
 */
public class OptionCheck extends OptionComponent implements ItemListener {

    private final JCheckBox check;

    public OptionCheck(RosterEntry rosterEntry, Option option) {
        super(rosterEntry, option);
        setLayout(new GridLayout(1, 1));
        check = new JCheckBox(option.toString(), getRosterEntry().hasOption(option));
        check.setToolTipText(composeTooltip());
        check.addItemListener(this);
        super.add(check);
        super.setMaximumSize(super.getPreferredSize());
        checkEnabled();
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        check.setEnabled(enabled);
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        switch (e.getStateChange()) {
            case ItemEvent.DESELECTED: {
                getRosterEntry().removeOption(getOption());
                fireOptionChanged(false);
                break;
            }
            case ItemEvent.SELECTED: {
                getRosterEntry().addOption(getOption());
                fireOptionChanged(true);
                break;
            }
        }
    }

    @Override
    public void select() {
        check.setSelected(true);
        // no need to fire any changes, it will be fired by ItemListener
    }

    @Override
    public void deselect() {
        check.setSelected(false);
        // no need to fire any changes, it will be fired by ItemListener
    }

}
